<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48" @keyup.enter.native="searchList">
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="任务编号">
                <a-input v-model="queryParam.taskNo" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="任务别名">
                <a-input v-model="queryParam.taskAliasName" placeholder="" allowClear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="任务类别">
                <a-select v-model="queryParam.taskTypes" mode="multiple" placeholder="请选择" :maxTagCount="2" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <!-- <a-select-option value="">不限</a-select-option> -->
                  <a-select-option :value="item.code" v-for="item in typeArr" :key="item.code">{{ item.text }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="支持小程序">
                <a-select v-model="queryParam.weIds" mode="multiple" placeholder="请选择" :maxTagCount="2" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <!-- <a-select-option value="">不限</a-select-option> -->
                  <a-select-option :value="item.weid" v-for="item in env === 'production' ? brandListPro : brandList" :key="item.weid">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="创建时间">
                <a-range-picker
                  style="width: 100%"
                  showToday
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryParam.regTime"
                />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 8px" type="primary" icon="plus" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.status" @change="tabsChange">
        <a-tab-pane :key="3" tab="全部"></a-tab-pane>
        <a-tab-pane :key="1" :tab="`进行中(${running})`"></a-tab-pane>
        <a-tab-pane :key="0" :tab="`未开始(${waiting})`"></a-tab-pane>
        <a-tab-pane :key="2" tab="已结束"></a-tab-pane>
      </a-tabs>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="queryParam.status == 3 ? allColums : columns" :data="loadData" :pagination="paginationProps">
        <span slot="weId" slot-scope="text">{{ text | brandName(env === 'production' ? brandListPro : brandList) }}</span>
        <span slot="taskType" slot-scope="text">{{ text | taskTypeName(typeArr) }}</span>
        <span slot="status" slot-scope="text">
          <a-badge status="success" text="进行中" v-if="text == 0" />
          <a-badge status="warning" text="未开始" v-if="text == 1" />
          <a-badge status="error" text="已结束" v-if="text == 2" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="record.taskType != 0 && record.taskType != 3">
            <router-link :to="`/marketingCenter/memberPromotions/memberTask/detail-list/${record.id}`">明细</router-link>
            <a-divider type="vertical" />
          </template>
          <router-link :to="`/marketingCenter/memberPromotions/memberTask/edit/${record.id}`" v-if="record.status == 1">编辑</router-link>
          <router-link :to="`/marketingCenter/memberPromotions/memberTask/edit/${record.id}`" v-else>查看</router-link>
          <a-divider type="vertical" />
          <router-link :to="`/marketingCenter/memberPromotions/memberTask/edit/${record.id}/copy`">复制</router-link>
          <a-divider type="vertical" />
          <a @click="handleLog(record.id)">日志</a>
          <template v-if="record.status != 2">
            <a-divider type="vertical" />
            <a-popconfirm title="确定上架吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record, 1)" v-if="record.status == 1">
              <a href="#">上架</a>
            </a-popconfirm>
            <a-popconfirm title="确定下架吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record, 2)" v-if="record.status == 0">
              <a href="#">下架</a>
            </a-popconfirm>
          </template>
          <template v-if="record.status != 0">
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record, 3)">
              <a href="#">删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
    </a-card>
    <AddModal ref="modalForm" @updateTable="refreshList"></AddModal>
    <LogModal ref="log" :logVisible.sync="logVisible"></LogModal>
    <a-modal :visible="visible" title="提示" @cancel="visible = false" @ok="handleHistory" okText="修改历史任务" cancelText="取消">
      <h3>存在同类型进行中的任务，无法上架</h3>
      <div v-for="(item, index) in clashTime" :key="item.id" style="margin-top: 12px">
        任务{{ index + 1 }}：【{{ item.brand | brandName(env === 'production' ? brandListPro : brandList) }}】{{ item.title }}<br />
        {{ item.startTime }} - {{ item.endTime }}
      </div>
    </a-modal>
  </div>
</template>
<script>
import { listMixin } from '@/views/box/util/listMixin'
import { taskMixin } from './mixin'
import { taskList, operateTask } from '@/api/marketingCenter/memberTask'
import AddModal from './AddModal'
import LogModal from './LogModal'
let columns = [
  { title: '任务编号', dataIndex: 'taskNo' },
  { title: '任务类别', dataIndex: 'taskType', scopedSlots: { customRender: 'taskType' }, width: 120 },
  { title: '任务别名', dataIndex: 'taskAliasName' },
  { title: '支持的小程序', dataIndex: 'weId', scopedSlots: { customRender: 'weId' }, width: 120 },
  { title: '排序值', dataIndex: 'sort', width: 100 },
  { title: '有效期', customRender: (t, r) => `${r.startTime}-${r.endTime}` },
  { title: '操作', fixed: 'right', width: 290, align: 'center', scopedSlots: { customRender: 'action' } }
]
let allColums = [...columns]
let status = { title: '状态', dataIndex: 'status', scopedSlots: { customRender: 'status' }, width: 100 }
allColums.splice(-1, 0, status)

export default {
  mixins: [listMixin, taskMixin],
  components: { AddModal, LogModal },
  data() {
    return {
      columns,
      allColums,
      running: 0,
      waiting: 0,
      queryParam: {
        status: 3,
        taskTypes: [],
        weIds: []
      },
      loadData: parameter => this.fetchData(parameter),
      logVisible: false,
      visible: false,
      clashTime: [],
      env: process.env.NODE_ENV
    }
  },
  watch: {
    $route(to, from) {
      let editPath = '/marketingCenter/memberPromotions/memberTask/edit'
      let detailPath = '/marketingCenter/memberPromotions/memberTask/detail-list'
      let currentPath = this.$route.path
      if ((from.path.includes(editPath) || from.path.includes(detailPath)) && to.path == currentPath) {
        this.$refs.table.refresh()
      } else if ((from.path.includes(currentPath) && to.path.includes(detailPath)) || to.path.includes(editPath)) {
        // console.log('***********keep***********')
      } else {
        /* if (to.path.includes(currentPath) && !from.path.includes('/marketingCenter/memberPromotions/memberTask')) {
          this.queryParam = {
            status: 3,
            taskType: '',
            weId: ''
          }
          this.tabsChange(3) // 刷新当前页面
        } */
        if (from.path.includes('/marketingCenter/memberPromotions/memberTask') && !to.path.includes('/marketingCenter/memberPromotions/memberTask')) {
          this.$destroy()
        }
      }
    }
  },
  methods: {
    fetchData(parameter) {
      let formValue = this.filterFields(this.queryParam)
      let params = {
        page: parameter,
        requestData: formValue
      }

      try {
        return this.fetchList(params, taskList).then(res => {
          if (res.code == 0) {
            this.running = res.data.running
            this.waiting = res.data.waiting
            return {
              data: res.data.rets,
              page: res.page
            }
          } else {
            return {
              data: [],
              page: {
                pageNo: 1,
                pageSize: 10,
                count: 0
              }
            }
          }
        })
      } catch (err) {
        console.log(err)
      }
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined && values[i] !== null) {
          if (i === 'regTime') {
            if (values[i].length) {
              formValue.startTime = values[i][0]
              formValue.endTime = values[i][1]
            }
          } else if (i === 'status') {
            if (values[i] != 3) {
              formValue[i] = values[i]
            }
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    resetList() {
      this.queryParam = {
        status: 3,
        taskTypes: [],
        weIds: []
      }
      this.$refs.table.refresh(true)
    },
    tabsChange(key) {
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    handleAdd() {
      this.$refs.modalForm.show()
    },
    handleEnable(record, type) {
      let params = {
        requestData: {
          id: record.id,
          status: type
        }
      }
      operateTask(params).then(res => {
        if (res.code == 0) {
          if (res.data.length) {
            this.visible = true
            this.clashTime = res.data.map(e => {
              return { ...e, timePicker: [e.startTime, e.endTime] }
            })
          } else {
            this.$message.success('成功')
            this.$refs.table.refresh()
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleLog(id) {
      this.$refs.log.getLog(id, 'parent')
      this.logVisible = true
    },
    handleHistory() {
      this.visible = false
      this.$router.push(`/marketingCenter/memberPromotions/memberTask/edit/${this.clashTime[0].id}`)
    }
  }
}
</script>

